<template>
  <q-page class="q-pa-md" v-loading="loading">
    <div style="position: relative">
      <q-breadcrumbs class="q-mb-md" style="height: 40px; line-height: 40px">
        <q-breadcrumbs-el label="项目信息" icon="bi-folder2-open" />
        <q-breadcrumbs-el label="成员" icon="bi-people" />
      </q-breadcrumbs>
      <div style="position: absolute; right: 0px; top: 10px">
        <el-button
          :disabled="isProjectCreate"
          @click="dialogVisible = true"
          type="primary"
          plain
          >添加成员</el-button
        >
      </div>
    </div>
    <div>
      <el-table :data="projectData">
        <el-table-column label="用户名" prop="user.username" width="150"></el-table-column>
        <el-table-column label="项目角色">
          <template #default="scope">
            <el-tag type="success">{{ scope.row.role }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="邮箱" prop="user.email"></el-table-column>
        <el-table-column label="加入时间">
          <template #default="scope">
            <span>{{ scope.row.date_join }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
          <!--v-if="userStatus && scope.row.role !== '项目创建人' && scope.row.user.username !== userInfoName"-->
            <!--                      <el-button @click="handleDelete(scope.$index, scope.row)" type="warning" size="small" plain>退出</el-button>-->
            <el-button
              v-if="userStatus && scope.row.user.username !== userInfoName && scope.row.role !== '项目创建人'"
              @click="deleteProjectMember(scope.row)"
              type="primary"
              size="small"
              >移出成员</el-button>
            <el-button v-if="isUserTransferProject.length > 0 && scope.row.user.username !== userInfoName" type="primary" size="small" @click="transferProjectDialog(scope.row)">转移项目</el-button>
            <el-button v-if="userStatus && scope.row.role !== '项目创建人'" type="primary" size="small" @click="permissionChange(scope.row)">权限修改</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--转移项目 start-->
    <el-dialog
      v-model="transferProjectDialogShow"
      :show-close="false"
      width="500px"
      :close-on-click-modal="false"
    >
      <template #header="{}">
        <div
          style="
            display: flex;
            justify-content: space-between;
            margin-top: 10px;
          "
        >
          <div style="display: flex">
            <el-icon style="font-size: 20px; color: rgb(250, 173, 21)"
            ><WarningFilled
            /></el-icon>
            <span style="margin-left: 10px; color: #1d1d1d; font-weight: bold"
            >转移提醒</span
            >
          </div>
        </div>
      </template>
      <div style="margin: 0 0 50px 50px; padding: 0">
        确定将项目转移给该用户嘛！请谨慎操作！
      </div>
      <div
        style="
          display: flex;
          justify-content: flex-end;
          margin-right: 10px;
          margin-bottom: 10px;
        "
      >
        <el-button type="primary" @click="transferProjectDialogShow = false">放弃</el-button>
        <el-button @click="transferProject">确定转移</el-button>
      </div>
    </el-dialog>
    <!--转移项目 end-->


    <el-dialog
      v-model="dialogVisible"
      title="邀请项目成员"
      width="600px"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <el-form
        style="padding: 0 50px"
        ref="memberFormRef"
        :model="memberForm"
        :rules="memberFormRules"
        :label-position="'left'"
        label-width="110px"
        status-icon
        @submit.prevent
      >
        <el-form-item label="用户邮箱" prop="email">
          <el-input spellcheck="false" v-model.trim="memberForm.email" placeholder="请输入用户邮箱" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item label="选择用户角色" prop="role_id">
          <el-radio-group v-model="memberForm.role_id" placeholder="请选择角色权限">
            <el-radio :disabled="projectAdministratorNumbers > 2" :label="2" style="width: 100%">项目管理员</el-radio>
            <el-radio :label="3" style="width: 100%">项目成员</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <div class="button" @click="closeDialog(memberFormRef)">取消</div>
          <div
            class="button"
            @click="addMember(memberFormRef)"
          >邀请</div>
        </span>
      </template>
    </el-dialog>

    <!--更改项目成员权限 start-->
    <el-dialog
      v-model="permissionChangeDialogShow"
      title="更改项目成员权限"
      width="600px"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <el-form
        style="padding: 0 50px"
        ref="memberFormRef"
        :model="memberForm"
        :rules="permissionChangeFormRules"
        :label-position="'left'"
        label-width="110px"
        status-icon
        @submit.prevent
      >
        <el-form-item label="选择用户角色" prop="role_id">
          <el-radio-group v-model="memberForm.role_id" placeholder="请选择角色权限">
            <el-radio :disabled="projectAdministratorNumbers > 2" :label="2" style="width: 100%">项目管理员</el-radio>
            <el-radio :label="3" style="width: 100%">项目成员</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <div class="button" @click="cancelPermission(memberFormRef)">取消</div>
          <div
            class="button"
            @click="permissionChangeBtn(memberFormRef)"
          >更改权限</div>
        </span>
      </template>
    </el-dialog>
    <!--更改项目成员权限 end-->

    <!--删除项目成员-->
    <el-dialog
      v-model="deleteProjectDialog"
      :show-close="false"
      width="500px"
      :close-on-click-modal="false"
    >
      <template #header="{}">
        <div
          style="
            display: flex;
            justify-content: space-between;
            margin-top: 10px;
          "
        >
          <div style="display: flex">
            <el-icon style="font-size: 20px; color: rgb(250, 173, 21)"
              ><WarningFilled
            /></el-icon>
            <span style="margin-left: 10px; color: #1d1d1d; font-weight: bold"
              >移出提醒</span
            >
          </div>
        </div>
      </template>
      <div style="margin: 0 0 50px 50px; padding: 0">
        确定移出该成员嘛?请谨慎操作！
      </div>
      <div
        style="
          display: flex;
          justify-content: flex-end;
          margin-right: 10px;
          margin-bottom: 10px;
        "
      >
        <el-button type="primary" @click="deleteProjectDialog = false">放弃</el-button>
        <el-button @click="emitDeleteMember">确认移出</el-button>
      </div>
    </el-dialog>
  </q-page>
</template>
<script setup lang="ts">
import type { FormInstance } from 'element-plus';
import { reactive, ref, toRaw } from 'vue';
import {
  addProjectMember,
  getProjectData,
  removeProjectMember,
  transfersProject,
  change_authority,
} from 'src/api/project';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import { isEmailUse } from 'src/api/model';
let projectData = ref([]);
let member_username = ref('');
let userId = ref('');
let isProjectCreate = ref(false); //判断是否为项目创建人
let projectIdData = ref({});//存储项目id
let permissionChangeData = ref({});
let isUserTransferProject = ref([]);//判断当前用户能否转移项目
let projectAdministratorNumbers = ref(0);//项目管理员人数
const router = useRouter();

let userStatus = JSON.parse(localStorage.getItem('user') || "{}").status;//判断用户是否是项目创建人或项目管理员
const userInfoName = localStorage.getItem('username')//获取用户登录的用户名


const loading = ref(true);
const dialogVisible = ref(false);
const deleteProjectDialog = ref(false);
const projectId = router.currentRoute.value.params.project_id;
const checkEmail = (rule: any, value: any, callback: any) => {
  // 邮箱正则表达式
  const regEmail = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{3,6}$/
  const params = reactive({
    email: memberForm.email
  })
  if (!value) {
    callback(new Error('请输入用户邮箱'))
  }
  if (regEmail.test(value)) {
      isEmailUse(projectId,params).then((res: any) => {
        console.log('res',res)
        callback();
      }).catch(error => {
        callback(new Error('系统没有该用户'))
      })
  }else {
      callback(new Error('请输入合法的邮箱!'))
  }

}//邮箱
const memberFormRules = reactive({
  email: [
    { required: true, validator: checkEmail, trigger: 'blur' },
  ],
  role_id: [{ required: true, message: '请选择用户权限', trigger: 'change' }],
});
//更改项目权限
const permissionChangeFormRules = reactive({
  role_id: [{ required: true, message: '请选择用户权限', trigger: 'change' }],
});
const memberFormRef = ref();
const memberForm = reactive({
  email: '',
  role_id: '',
});

//转移项目
let transferProjectDialogShow = ref(false);
function transferProjectDialog (row:any) {
  projectIdData.value = row;
  transferProjectDialogShow.value = true;
}
function transferProject () {
  let data = JSON.parse(JSON.stringify(projectIdData.value));
  const params = {
    member_username: data.user.username
  }
  transfersProject(projectId,params).then( res =>{
    ElMessage.success(`转移成功！`);
    let userData = JSON.parse(localStorage.getItem('user') || "{}");
    userData.is_admin = false;
    userData.status = false;
    localStorage.setItem('user', JSON.stringify(userData));
    transferProjectDialogShow.value = false;
    userStatus = false;
    getUserList();//再次获取成员列表
  })
}
//权限修改
let permissionChangeDialogShow = ref(false);
function permissionChange (row:any) {
  permissionChangeData.value = row;
  permissionChangeDialogShow.value = true;
  userId.value = toRaw(row.user.id);
}
function permissionChangeBtn (formEl: FormInstance | undefined) {
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (valid) {
      const data = JSON.parse(JSON.stringify(permissionChangeData.value));
      change_authority(projectId,userId.value,{
        role_id: memberForm.role_id
      }).then( res => {
        ElMessage.success('权限修改成功!');
        getUserList();//再次获取成员列表
        formEl.resetFields();
        permissionChangeDialogShow.value = false;
      })
    }
  })
}
function cancelPermission (formEl: FormInstance | undefined) {
  if (!formEl) return;
  formEl.resetFields();
  permissionChangeDialogShow.value = false
}


function addMember(formEl: FormInstance | undefined) {
  if (!formEl) return;
  memberFormRef.value.validate().then((valid: any) => {
    if (valid) {
      addProjectMember(projectId, memberForm)
        .then((res) => {
          loading.value = true;
          dialogVisible.value = false;
          ElMessage.success('添加成功');
          getUserList();
          formEl.resetFields();//清空表单
        })
    }
  });
}

//获取项目成员列表
getUserList();
function getUserList() {
  loading.value = true;
  getProjectData(projectId)
    .then((response) => {
      const userName = localStorage.getItem('username');
      const userInfo = response.data.filter(
        (items: any) => items.user.username === userName
      );
      isUserTransferProject.value =  response.data.filter( (item:any) => item.user.username === userInfoName && item.role === '项目创建人' );//判断登录的用户是否有转移项目的权限
      projectAdministratorNumbers.value = response.data.filter( (item:any) => item.role === '项目管理员' ).length;
      response.data.forEach( (item:any) => {
        if(item.user.username === userInfoName && item.role === '项目成员'){
          //如果修改用户权限为项目成员
          let userData = JSON.parse(localStorage.getItem('user') || "{}");
          userData.is_admin = false;
          userData.status = false;
          userStatus = false;
          localStorage.setItem('user', JSON.stringify(userData));
        }
      });
      projectData.value = response.data;
      if (userInfo[0].role !== '项目创建人' && userInfo[0].role !== '项目管理员') {
        isProjectCreate.value = true
      }
      loading.value = false;
    })
    .finally(() => {
      loading.value = false;
    });
}

function deleteProjectMember(row: any) {
  deleteProjectDialog.value = true;
  member_username.value = toRaw(row.user.username);
  userId.value = toRaw(row.user.id);
}

//确定删除项目成员
function emitDeleteMember() {
  removeProjectMember(projectId,userId.value).then((res) => {
    ElMessage.success('移除成功!!!');
    deleteProjectDialog.value = false;
    getUserList();
  });
}

//取消关闭弹框
const closeDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  dialogVisible.value = false;
};
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__header {
  margin: 0;
  border-bottom: 1px solid;
}
.dialog-footer {
  display: flex;
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  border-top: 1px solid;
  .button {
    cursor: pointer;
    width: 50%;
    margin: 0;
    border: none;
    text-align: center;
    line-height: 40px;
  }
  .button:nth-child(1){
    color: #1d1d1d;
    border-right: 1px solid;
  }
  .button:nth-child(2){
    color: #1b5bd8;
  }
}
</style>
